package sweetguy.mapper;

import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import sweetguy.entity.dto.Permission;

import java.util.List;

@Repository
public interface PermissionMapper {
    @Insert("insert into ums_permission " +
            "(`title`, `url`, `icon`, `pid`, `info`," +
            "`deleted`, `created`, `updated`) " +
            "values (#{title}, #{info}," +
            "#{deleted}, #{created}, #{updated})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Permission permission);

    @Select("select us.id, us.title, us.url, us.icon, us.pid, us.info," +
            "us.deleted, us.created, us.updated from ums_permission us " +
            "where us.id = #{param1} and us.deleted = 0")
    Permission selectById(Long id);

    @Update("<script>" +
            "update ums_permission " +
            "<set> " +
            "<if test='title != null'> title = #{title}, </if> " +
            "<if test='url != null'> url = #{url}, </if> " +
            "<if test='icon != null'> icon = #{icon}, </if> " +
            "<if test='pid != null'> pid = #{pid}, </if> " +
            "<if test='info != null'> info = #{info}, </if> " +
            "<if test='deleted != null'> deleted = #{deleted}, </if> " +
            "<if test='created != null'> created = #{created}, </if> " +
            "<if test='updated != null'> updated = #{updated}, </if> " +
            "</set> " +
            "where id = #{id} and deleted = 0" +
            "</script>")
    int updateById(Permission permission);

    @Update("update ums_permission set deleted = 1, updated = now() where id = #{id}")
    int logicDeleteById(Long id);

    @Update("<script>" +
            "update ums_permission set deleted = 1, updated = now() where " +
            "<foreach collection='list' item='e' open='id in (' close=')' separator=','>" +
            "${e}" +
            "</foreach>" +
            "</script>")
    int logicDeleteByIds(List<Long> ids);

    @Select("select us.id, us.title, us.info, us.url, us.icon, us.pid," +
            "us.deleted, us.created, us.updated from ums_permission us where us.deleted = 0")
    List<Permission> list();

    @Select("select us.title, " +
            "us.deleted, us.created, us.updated from ums_room us " +
            "where us.title = #{title} " )
    Permission selectByAllTitle(Permission permission);

    @Delete("delete from ums_permission where id = #{param1}")
    int deleteById(Long id);

    @Select("select up.id, up.title, up.url, up.icon, up.pid, " +

            "up.deleted, up.created, up.updated " +

            "from ums_permission up where up.id in( " +

            "select urp.fk_permission_id from ums_role_permission urp " +

            "where fk_role_id in ( " +

            "select ue.fk_role_id from ums_emp_role ue where ue.fk_emp_id = #{param1}))")
    List<Permission> selectByEmpId(Long empId);
}
